In this lesson we learn about the basic data types and data structures and play with them a little.
Lets start by initializing integer, string, list and dictionary
In [1]:
integer = 99
string = 'poonacha'
print('This is an integer: ',integer )
print('This is a string: ',string )
Most integer/floating point operators that you use in stata or other languages work in python as well - eg (+,-,*,/).
Let us write a code to find the quotient and reminder of a number given a divisor. The operator '//' can be used to find the quotient and '%' can be used to find the reminder.
In [2]:
number = 199
divisor = 10
rem = 199 % 10
quotient = 199 // 10
print('reminder = ', rem,'quotient = ', quotient)
Data structures combine the basic datatypes (integer, float, string, boolean) to create more complex types. There are several types of data structures but the most commonly used ones are "lists" and "dictionaries"
We start with a list. A list is a sequence of integer / character data types. Let us now create two list's one with only integer data "i_list" and the other with only character data "c_list".
In [3]:
i_list = [1,2,3,4]
c_list = ['day','month','year']
print('This is an integer list: ',i_list )
print('This is a char list: ',c_list )
The elements in the lists are numbered upwards from 0. Hence, we can access each element in the list using its index number. The following code prints the first element of c_list.
In [4]:
print('The first element is: ', c_list[0])
In [5]:
i_list = [1,2,3,4]
# Append the number 5 at the end
i_list.append(5)
print(i_list)
# Insert the 1.5 between 1 and 2
i_list.insert(1,1.5)
print(i_list)
#delete the number 1.5
del i_list[1]
print(i_list)
#delete the number between position 0 and 2
del i_list[0:2]
print(i_list)
#delete the entire list
del i_list[:]
print(i_list)
In [6]:
string = 'poonacha'
string = string + ' medappa'
print(string)
print(string[0:3])
Let us write a code to enter a sentence and split it into a list of words.
In [7]:
s_input = input('Enter the sentence to be split: ')
words = s_input.split()
print(words)
print(words[0])
In [0]:
# Enter Code
In [8]:
dict_date = {'day' : 14 , 'month' : 3, 'year' : 2018}
print('This is a dictionary: ',dict_date)
print('Today in dictionary is: day - ',dict_date['day'],' month - ',dict_date['month'],' year - ', dict_date['year'] )